// router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginComponent from '../views/LoginComponent/LoginComponent.vue'
import RegisterComponent from '../views/RegisterComponent/RegisterComponent.vue'
import TransactionComponent from '../views/TransactionComponent/TransactionComponent.vue'
import BudgetsComponent from '../views/BudgetsComponent/BudgetsComponent.vue'
import HomeComponent from '../views/HomePage.vue'

Vue.use(VueRouter)

const routes = [
  { path: '/', component: HomeComponent },
  { path: '/login', component: LoginComponent },
  { path: '/register', component: RegisterComponent },
  { path: '/transaction', component: TransactionComponent },
  { path: '/budgets', component: BudgetsComponent }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem('token')
  if (to.name === 'login' && localStorage.getItem('userLoggedIn')) {
    next('/') // 如果用户已登录，则重定向到首页
  } else {
    next() // 否则允许继续导航
  }
  // 如果用户已登录，则允许导航
  if (isLoggedIn) {
    next()
  } else {
    // 如果用户未登录，并且目标路由不是登录页，则重定向到登录页
    if (to.path !== '/login' && to.path !== '/register') {
      next('/login')
    } else {
      next() // 允许访问登录页
    }
  }
})

export default router
